<template>
  <view class="w-full max-w-[750rpx] mx-auto min-h-screen bg-[#f6f8fa] p-[32rpx] box-border">
    <text class="block text-[48rpx] font-extrabold mb-[40rpx] text-center text-blue-600 drop-shadow">{{ pageTitle }}</text>
    <FormView v-if="form.recordid" :fieldConfig="fieldConfig" :form="form" :showButtons="true" @submit="submitForm" />
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import Taro from '@tarojs/taro'
import FormView from '@/components/FormView.vue'
import { request } from '@/service/request'
import { localStg } from '@/utils'

interface FormConfig {
  pageTitle: string
  fieldConfig: any
  addApi: string
  editApi: string
  queryByIdApi: string
  successMessage: string
  errorMessage: string
}

interface Props {
  config: FormConfig
  mode: 'add' | 'edit'
}

const props = defineProps<Props>()

const form = reactive<any>({})
const recordId = ref<string>('')

const pageTitle = computed(() => props.config.pageTitle)
const fieldConfig = computed(() => props.config.fieldConfig)

onMounted(async () => {
  if (props.mode === 'add') {
    // 新增模式：初始化表单数据
    const obj = localStg.get("demographicInfo");
    if(obj){
      form.name = obj.name;
      form.idNumber = obj.idNumber;
      form.recordid = obj.recordid;
    }
  } else {
    // 编辑模式：获取路由参数并加载数据
    const params = Taro.getCurrentInstance().router?.params
    if (params?.id) {
      recordId.value = params.id
      await loadRecordData(params.id)
    }
  }
})

async function loadRecordData(id: string) {
  try {
    const result = await request.get<any>(`${props.config.queryByIdApi}?id=${id}`, {}, {
      useErrMsg: true
    })

    console.log("result", result)
    
    if (result.success) {
      // 处理从后端返回的数据，将多选框的逗号分隔字符串转换为数组
      const processedData = { ...result.success };
      Object.keys(props.config.fieldConfig).forEach((key) => {
        const cfg = props.config.fieldConfig[key];
        if (cfg.type === 'checkbox' && typeof processedData[key] === 'string' && processedData[key]) {
          processedData[key] = processedData[key].split(',').map(item => item.trim());
        }
      });
      
      Object.assign(form, processedData);
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    Taro.showToast({ title: '加载数据失败', icon: 'error' })
  }
}

async function submitForm(form: any, fieldConfig: any) {
  try {
    const params = { ...form }
    
    let result
    if (props.mode === 'add') {
      result = await request.post<any>(props.config.addApi, params, {
        useErrMsg: true
      })
    } else {
      result = await request.put<any>(props.config.editApi, params, {
        useErrMsg: true
      })
    }
    
    if (result) {
      Taro.showToast({ title: props.config.successMessage, icon: 'success' })
      setTimeout(() => {
        Taro.navigateBack()
      }, 1500)
    }
  } catch (error) {
    console.error('保存失败:', error)
    Taro.showToast({ title: props.config.errorMessage, icon: 'error' })
  }
}
</script>
